package com.potenza.training.reply.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("reply/oss")
public class OssFileUpload {

    @Autowired
    private OSS ossClient;

    @Value("${oss.hostName}")
    private String hostName;

    @Value("${oss.bucket}")
    private String bucket;

    //图片上传
    @RequestMapping("/uplode")
    public String uplode(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        ossClient.putObject(bucket, originalFilename, file.getInputStream());

        String imageUrl = "https://" + bucket + "." + hostName + "/" + originalFilename;

        return imageUrl+","+originalFilename;
    }


    @PostMapping("/audiofile")
    public R imagefile(@RequestParam("audio") MultipartFile file) throws IOException {
        long size = file.getSize();
        System.out.println(size+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        String filename1 = file.getOriginalFilename();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        ossClient.putObject(bucket,format+filename1,file.getInputStream());
        String message="https://"+bucket+"."+hostName+"/"+filename1;
        return R.ok().put("messages",message);
    }

    @PostMapping("/videofile")
    public R base64UploadImage(@RequestBody Map saveMap) {
        // 接收到前端传递的 base64字符串 编码
        String baseUrl = saveMap.get("videoUrl").toString();
        //去掉头部信息
        String imgdata = baseUrl.replace("data:video/x-matroska;base64,","");
        //解码 并转为图片 保存本地
        R r = GenerateImage(imgdata);
        return r;
    }

    //base64字符串转化成图片
    public  R GenerateImage(String imgStr)
    {   //对字节数组字符串进行Base64解码并生成图片
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] bytes = new BASE64Decoder().decodeBuffer(imgStr);  //将字符串转换为byte数组，这里的content是那一串base64密文 /9j/4AAQ.................，不包含（data:img/jpg;base64,）注意标点符号
            InputStream inputStream = new ByteArrayInputStream(bytes);
            //生成jpeg图片
            //时间long+随机数 生成文件名字
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String format = String.valueOf(date.getTime());
            SecureRandom random = new SecureRandom();
            int ends = random.nextInt(99);
            String.format("%02d",ends);//如果不足两位，前面补0
            //指定图片的路径
            String imgFilePath = format + ends + ".mkv";//新生成的视频

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());
            ossClient.putObject(bucket, imgFilePath, inputStream,metadata);
            String imageurl = "https://" + bucket + "." + hostName + "/" + imgFilePath;
            return  R.ok().put("imageUrl",imageurl);
        }
        catch (Exception e)
        {
            return R.error();
        }
    }

}
